package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.POCourseDao;
import com.huike.pmps.dao.POCourseSupplierDetailDao;
import com.huike.pmps.dao.SupplierDao;
import com.huike.pmps.dao.SupplierSettlementDetailDao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.*;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.service.*;
import com.huike.pmps.utils.PmpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Service
@Slf4j
public class POCourseSupplierDetailServiceImpl implements POCourseSupplierDetailService {
    @Autowired
    POCourseSupplierDetailDao poCourseSupplierDetailDao;
    @Autowired
    SupplierSettlementDetailDao supplierSettlementDetailDao;
    @Autowired
    SupplierSettlementDetailService supplierSettlementDetailService;
    @Autowired
    POCourseService poCourseService;
    @Autowired
    SupplierDao supplierDao;
    @Autowired
    SupplierService supplierService;
    @Autowired
    DictionaryService dictionaryService;
    @Autowired
    POCourseDao poCourseDao;

    /**
     * 给课程分配供应商
     *
     * @param poCourseSupplierDetail
     * @return
     */
    @Override
    public Result insertOne(POCourseSupplierDetail poCourseSupplierDetail) {
        //获取课程相信信息
        POCourse poCourse = poCourseService.selectById(poCourseSupplierDetail.getPoCourseId());
        BeanUtils.copyProperties(poCourse, poCourseSupplierDetail, new String[]{"id", "rowEdit", "supplierPaidAmount", "supplierUnpaidAmount","estimatedSettlementDate", "state", "updateTime", "createTime"});
        //字段相关字段值
        calculatePoCourseSupplierDetail(poCourseSupplierDetail);

        //设置课程启动时间,第一次修改或者分配供应商的时间
        if(poCourse.getStartTime() == null){
            poCourseDao.updateStartTimeById(poCourse.getId(), new Date());
        }
        poCourseSupplierDetailDao.insert(poCourseSupplierDetail);
        //供应商已承接的课程+1
        supplierDao.updateAddNumberOfCourse(poCourseSupplierDetail.getSupplierId());
        return Result.success();
    }

    /**
     * 供应商分配总表
     *
     * @param pageInfo
     * @return
     */
    @Override
    public Result selectByCondition(Member member, PageInfo pageInfo, String po, String customerName, String regionName, String provinceName, String courseName, String courseChargeName, String supplierName) {
        QueryWrapper<POCourseSupplierDetail> queryWrapper = new QueryWrapper<>();


        if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_ADMIN)) {//管理员
        } else if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_REGION)) {//战区司令
            if (member.getRegionId() == null) return Result.failure("您的账号没有配置所属战区，请联系 系统管理员 进行战区配置");
            queryWrapper.eq("region_id", member.getRegionId());
        } else {
            if (member.getProvinceId() == null) return Result.failure("您的账号没有配置所属省区，请联系 系统管理员 进行省区配置");
            queryWrapper.eq("province_id", member.getProvinceId());
        }


        if (StringUtils.isNotBlank(po))
            queryWrapper.like("po", po);

        if (StringUtils.isNotBlank(customerName))
            queryWrapper.like("customer_name", customerName);

        if (StringUtils.isNotBlank(regionName))
            queryWrapper.like("region_name", regionName);

        if (StringUtils.isNotBlank(provinceName))
            queryWrapper.like("province_name", provinceName);

        if (StringUtils.isNotBlank(courseName))
            queryWrapper.like("course_name", courseName);

        if (StringUtils.isNotBlank(courseChargeName))
            queryWrapper.like("course_charge_name", courseChargeName);

        if (StringUtils.isNotBlank(supplierName))
            queryWrapper.like("supplier_name", supplierName);

        queryWrapper.orderByDesc("id");

        Page<POCourseSupplierDetail> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<POCourseSupplierDetail> pageList = poCourseSupplierDetailDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }
    }

    /**
     * 根据ID更新课程供应商信息
     *
     * @param poCourseSupplierDetail
     * @return
     */
    @Override
    public Result updateById(POCourseSupplierDetail poCourseSupplierDetail) {
        poCourseSupplierDetail.setRowEdit(false);
        //字段相关字段值
        calculatePoCourseSupplierDetail(poCourseSupplierDetail);
        poCourseSupplierDetail.setUpdateTime(new Date());
        //更新课程供应商信息
        if (poCourseSupplierDetailDao.updateById(poCourseSupplierDetail) > 0) {
            //更新对应的结算单
            if (poCourseSupplierDetail.getState() == GlobalConstants.PO_COURSE_SUPPLIER_STATE_JSD) {
                //结算单
                SupplierSettlementDetail supplierSettlementDetail = new SupplierSettlementDetail();
                BeanUtils.copyProperties(poCourseSupplierDetail, supplierSettlementDetail, new String[]{"id", "state", "rowEdit", "createTime"});
                //按课程供应商id更新对应的结算单
                UpdateWrapper<SupplierSettlementDetail> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("po_course_supplier_id", poCourseSupplierDetail.getId());
                supplierSettlementDetailDao.update(supplierSettlementDetail, updateWrapper);
            }

            return Result.success();
        } else {
            return Result.failure("更新失败");
        }

    }

    /**
     * 根据ID删除记录
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        Result result = supplierSettlementDetailService.selectOneByPOCourseSupplierId(id);
        if (result.getData() != null) return Result.failure("请先删除结算清单");
        Integer supplierId = poCourseSupplierDetailDao.selectById(id).getSupplierId();
        //供应商已承接的课程-1
        supplierDao.updateMinusNumberOfCourse(supplierId);
        poCourseSupplierDetailDao.deleteById(id);
        return Result.success();
    }

    /**
     * 根据ID查询记录
     *
     * @param id
     * @return
     */
    @Override
    public Result selectById(Integer id) {
        POCourseSupplierDetail poCourseSupplierDetail = poCourseSupplierDetailDao.selectById(id);
        return Result.success(poCourseSupplierDetail);
    }

    /**
     * 根据课程主键poCourseId查询课程下的供应商
     *
     * @param poCourseId
     * @return
     */
    @Override
    public Result selectByPoCourseId(Integer poCourseId) {
        QueryWrapper<POCourseSupplierDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("po_course_id", poCourseId);
        List<POCourseSupplierDetail> courseList = poCourseSupplierDetailDao.selectList(queryWrapper);
        if (courseList.size() > 0) {
            return Result.success(courseList);
        } else {
            return Result.failure("没有可查询的数据");
        }

    }

    @Override
    public void exportCourseSupplier(HttpServletResponse response, String po, String customerName, String regionName, String provinceName, String courseName, String courseChargeName, String supplierName, Member member) {
        QueryWrapper<POCourseSupplierDetail> queryWrapper = new QueryWrapper<>();


        if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_ADMIN)) {//管理员
        } else if (member.getRolesIds().contains(GlobalConstants.SYSTEM_ROLE_REGION)) {//战区司令
            queryWrapper.eq("region_id", member.getRegionId());
        } else {
            queryWrapper.eq("province_id", member.getProvinceId());
        }

        if (StringUtils.isNotBlank(po))
            queryWrapper.like("po", po);

        if (StringUtils.isNotBlank(customerName))
            queryWrapper.like("customer_name", customerName);

        if (StringUtils.isNotBlank(regionName))
            queryWrapper.like("region_name", regionName);

        if (StringUtils.isNotBlank(provinceName))
            queryWrapper.like("province_name", provinceName);

        if (StringUtils.isNotBlank(courseName))
            queryWrapper.like("course_name", courseName);

        if (StringUtils.isNotBlank(courseChargeName))
            queryWrapper.like("course_charge_name", courseChargeName);

        if (StringUtils.isNotBlank(supplierName))
            queryWrapper.like("supplier_name", supplierName);

        List<POCourseSupplierDetail> poCourseSupplierDetailList = poCourseSupplierDetailDao.selectList(queryWrapper);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("export_excel/course_supplier_template.xlsx");
        XSSFWorkbook xssfWorkbook = null;
        try {
            xssfWorkbook = new XSSFWorkbook(in);
            //获取第一个工作表sheet
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
            for (int i = 0; i < poCourseSupplierDetailList.size(); i++) {
                POCourseSupplierDetail poCourseSupplierDetail = poCourseSupplierDetailList.get(i);
                XSSFRow row = sheetAt.createRow(i + 1);

                //po单号
                XSSFCell poCell = row.createCell(0);
                poCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(poCourseSupplierDetail.getPo()))
                    poCell.setCellValue(poCourseSupplierDetail.getPo());

                //课程ID
                XSSFCell courseIdCell = row.createCell(1);
                courseIdCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getCourseId() != null)
                    courseIdCell.setCellValue(poCourseSupplierDetail.getCourseId());

                //课程名称
                XSSFCell courseNameCell = row.createCell(2);
                courseNameCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getCourseName() != null)
                    courseNameCell.setCellValue(poCourseSupplierDetail.getCourseName());

                //课程经理/课程编导
                XSSFCell courseChargeNameCell = row.createCell(3);
                courseChargeNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(poCourseSupplierDetail.getCourseChargeName()))
                    courseChargeNameCell.setCellValue(poCourseSupplierDetail.getCourseChargeName());


                //供应商类型名称
                XSSFCell supplierTypeNameCell = row.createCell(4);
                supplierTypeNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(poCourseSupplierDetail.getSupplierTypeName()))
                    supplierTypeNameCell.setCellValue(poCourseSupplierDetail.getSupplierTypeName());

                //供应商名称
                XSSFCell supplierNameCell = row.createCell(5);
                supplierNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(poCourseSupplierDetail.getSupplierName()))
                    supplierNameCell.setCellValue(poCourseSupplierDetail.getSupplierName());

                //服务类型名称
                XSSFCell serviceTypeNameCell = row.createCell(6);
                serviceTypeNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(poCourseSupplierDetail.getServiceTypeName()))
                    serviceTypeNameCell.setCellValue(poCourseSupplierDetail.getServiceTypeName());


                //服务名称
                XSSFCell serviceNameCell = row.createCell(7);
                serviceNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(poCourseSupplierDetail.getServiceName()))
                    serviceNameCell.setCellValue(poCourseSupplierDetail.getServiceName());


                //更新日期
                XSSFCell updateTimeCell = row.createCell(8);
                updateTimeCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getUpdateTime() != null)
                    updateTimeCell.setCellValue(simpleDateFormat.format(poCourseSupplierDetail.getUpdateTime()));

                //预估结算日期
                XSSFCell estimatedSettlementDateCell = row.createCell(9);
                estimatedSettlementDateCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getEstimatedGenerationCost() != null)
                    estimatedSettlementDateCell.setCellValue(simpleDateFormat.format(poCourseSupplierDetail.getEstimatedGenerationCost()));


                //单价
                XSSFCell unitPriceCell = row.createCell(10);
                unitPriceCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getUnitPrice() != null)
                    unitPriceCell.setCellValue(poCourseSupplierDetail.getUnitPrice().toString());

                //数量
                XSSFCell quantityCell = row.createCell(11);
                quantityCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getQuantity() != null)
                    quantityCell.setCellValue(poCourseSupplierDetail.getQuantity());

                //预估成本
                XSSFCell estimatedGenerationCostCell = row.createCell(12);
                estimatedGenerationCostCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getEstimatedGenerationCost() != null)
                    estimatedGenerationCostCell.setCellValue(poCourseSupplierDetail.getEstimatedGenerationCost().toString());

                //已支付
                XSSFCell supplierPaidAmountCell = row.createCell(13);
                supplierPaidAmountCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getSupplierPaidAmount() != null)
                    supplierPaidAmountCell.setCellValue(poCourseSupplierDetail.getSupplierPaidAmount().toString());

                //未支付
                XSSFCell supplierUnpaidAmountCell = row.createCell(14);
                supplierUnpaidAmountCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getSupplierUnpaidAmount() != null)
                    supplierUnpaidAmountCell.setCellValue(poCourseSupplierDetail.getSupplierUnpaidAmount().toString());

                //供应商评级
                XSSFCell finalEvaluationCell = row.createCell(15);
                finalEvaluationCell.setCellType(CellType.STRING);
                if (poCourseSupplierDetail.getFinalEvaluation() != null)
                    finalEvaluationCell.setCellValue(poCourseSupplierDetail.getFinalEvaluation());

                //说明
                XSSFCell descriptionCell = row.createCell(16);
                descriptionCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(poCourseSupplierDetail.getDescription()))
                    descriptionCell.setCellValue(poCourseSupplierDetail.getDescription());
            }
            String fileName = "course_supplier_" + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + ".xlsx";
            response.setContentType("application/octet-stream"); // 响应内容格式
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            xssfWorkbook.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 导入 课程-供应商数据
     *
     * @param file
     * @return
     */
    @Override
    public Result insertByImportPOCourseSupplierDetail(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure("文件为空");
        }
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            //根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取标题行
            XSSFRow titleRow = sheet.getRow(0);
            String[] titleRowArray = new String[]{"课程ID", "供应商名称", "服务类型", "服务名称", "更新日期", "预估结算日期", "单价", "数量", "预估成本", "已支付", "未支付", "供应商评级", "说明", "服务ID"};
            for (int i = 0; i < titleRowArray.length; i++) {
                if (!titleRowArray[i].equals(titleRow.getCell(i).toString()))
                    return Result.failure("模板标题行已被修改，请勿修改合同模板标题行");
            }
            //日期格式化
            //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            //实体类集合
            List<POCourseSupplierDetail> poCourseSupplierDetailList = new ArrayList<>();

            XSSFRow row = null;
            //循环sesheet页中数据从第二行开始，第一行是标题
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                row = sheet.getRow(i);

                if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据的 课程ID 为空");
                if (row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据的 供应商名称 为空");
                if (row.getCell(13) == null || StringUtils.isBlank(row.getCell(13).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据的 服务ID 为空");
               /* if (row.getCell(2) == null || StringUtils.isBlank(row.getCell(2).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据的 服务类型 为空");*/

                //实体对象
                POCourseSupplierDetail poCourseSupplierDetail = new POCourseSupplierDetail();


                //课程ID
                Long courseId = Double.valueOf(row.getCell(0).toString()).longValue();
                poCourseSupplierDetail.setCourseId(courseId);
                POCourse poCourse = poCourseService.selectOneByImportCourseId(courseId);
                if (poCourse != null) {
                    BeanUtils.copyProperties(poCourse, poCourseSupplierDetail, new String[]{"id", "rowEdit", "state", "updateTime", "createTime"});
                    //设置课程-供应商对应的课程ID
                    poCourseSupplierDetail.setPoCourseId(poCourse.getId());
                } else {
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据，在课程列表中找不到该课程,请确保对应的课程已经导入到系统中");
                }
                //获取供应商信息
                log.info("供应商名称"+row.getCell(1).toString());
                Supplier supplier = supplierService.selectOneBySupplierName(row.getCell(1).toString());
                if (supplier != null) {
                    poCourseSupplierDetail.setSupplierId(supplier.getId());
                    poCourseSupplierDetail.setSupplierName(supplier.getSupplierName());
                    poCourseSupplierDetail.setSupplierTypeId(supplier.getSupplierTypeId());
                    poCourseSupplierDetail.setSupplierTypeName(supplier.getSupplierTypeName());
                } else {
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据，在供应商列表中找不到该该供应商信息，请确保该供应商已导入到系统中");
                }

                if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
                    //服务类型
                    Dictionary dictionary = dictionaryService.selectByOne(row.getCell(2).toString(), GlobalConstants.DICTIONARY_SUPPLIER_SERVICE_CONTENT_TYPE);
                    if (dictionary != null) {
                        poCourseSupplierDetail.setServiceTypeId(dictionary.getId());
                        poCourseSupplierDetail.setServiceTypeName(dictionary.getName());
                    }
               /* else {
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据，在供应商服务类型有误");
                }*/
                }


                //服务名称
                String serviceName = row.getCell(3) == null || StringUtils.isBlank(row.getCell(3).toString()) ? null : row.getCell(3).toString();
                poCourseSupplierDetail.setServiceName(serviceName);

                //更新日期
                Date updateTime = row.getCell(4) == null || StringUtils.isBlank(row.getCell(4).toString()) ? null : row.getCell(4).getDateCellValue();
                poCourseSupplierDetail.setUpdateTime(updateTime);

                //预估结算日期
                Date estimatedSettlementDate = row.getCell(5) == null || StringUtils.isBlank(row.getCell(5).toString()) ? null : row.getCell(5).getDateCellValue();
                poCourseSupplierDetail.setEstimatedSettlementDate(estimatedSettlementDate);

                //单价
                BigDecimal unitPrice = row.getCell(6) == null || StringUtils.isBlank(row.getCell(6).toString()) ? null : BigDecimal.valueOf(Double.valueOf(row.getCell(6).toString()));
                poCourseSupplierDetail.setUnitPrice(unitPrice);

                //数量
                Double quantity = row.getCell(7) == null || StringUtils.isBlank(row.getCell(7).toString()) ? null : Double.valueOf(row.getCell(7).toString());
                poCourseSupplierDetail.setQuantity(quantity);

                //预估成本
                BigDecimal estimatedGenerationCost = row.getCell(8) == null || StringUtils.isBlank(row.getCell(8).toString()) ? null : BigDecimal.valueOf(Double.valueOf(row.getCell(8).toString()));
                poCourseSupplierDetail.setEstimatedGenerationCost(estimatedGenerationCost);

                //已支付
                BigDecimal supplierPaidAmount = row.getCell(9) == null || StringUtils.isBlank(row.getCell(9).toString()) ? null : BigDecimal.valueOf(Double.valueOf(row.getCell(9).toString()));
                poCourseSupplierDetail.setSupplierPaidAmount(supplierPaidAmount);

                //未支付
                BigDecimal supplierUnpaidAmount = row.getCell(10) == null || StringUtils.isBlank(row.getCell(10).toString()) ? null : BigDecimal.valueOf(Double.valueOf(row.getCell(10).toString()));
                poCourseSupplierDetail.setSupplierUnpaidAmount(supplierUnpaidAmount);

                //数量
                Double finalEvaluation = row.getCell(11) == null || StringUtils.isBlank(row.getCell(11).toString()) ? null : Double.valueOf(row.getCell(11).toString());
                poCourseSupplierDetail.setFinalEvaluation(finalEvaluation);

                //描述
                String description = row.getCell(12) == null || StringUtils.isBlank(row.getCell(12).toString()) ? null : row.getCell(12).toString();
                poCourseSupplierDetail.setDescription(description);

                //服务ID
                Integer importServiceId = row.getCell(13) == null || StringUtils.isBlank(row.getCell(13).toString()) ? null : Double.valueOf(row.getCell(13).toString()).intValue();
                poCourseSupplierDetail.setImportServiceId(importServiceId);

                poCourseSupplierDetail.setUpdateTime(new Date());
                poCourseSupplierDetail.setCreateTime(new Date());
                poCourseSupplierDetail.setState(GlobalConstants.PO_COURSE_SUPPLIER_STATE_INIT);
                poCourseSupplierDetail.setRowEdit(false);
                poCourseSupplierDetailList.add(poCourseSupplierDetail);
            }
            if (poCourseSupplierDetailList.size() > 0) {
                poCourseSupplierDetailDao.insertBatchList(poCourseSupplierDetailList);
                return Result.success();
            } else {
                return Result.failure("表格中没有数据，导入失败");
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.failure("导入失败，请检查数据格式是否符合模板要求：" + e.getMessage());
        }
    }

    @Override
    public POCourseSupplierDetail selectOneByImportServiceId(Integer importServiceId) {
        QueryWrapper<POCourseSupplierDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("import_service_id", importServiceId);
        queryWrapper.eq("import_flag", 2);
        return poCourseSupplierDetailDao.selectOne(queryWrapper);
    }

    /**
     * 计算相关属性
     *
     * @param poCourseSupplierDetail
     * @return
     */
    private void calculatePoCourseSupplierDetail(POCourseSupplierDetail poCourseSupplierDetail) {

        if (poCourseSupplierDetail.getUnitPrice() != null && poCourseSupplierDetail.getQuantity() != null) {
            poCourseSupplierDetail.setEstimatedGenerationCost(
                    BigDecimal.valueOf(PmpUtil.getScale(poCourseSupplierDetail.getUnitPrice().doubleValue() * poCourseSupplierDetail.getQuantity(), 2))
            );
        }
        POCourseSupplierDetail detail = poCourseSupplierDetailDao.selectById(poCourseSupplierDetail.getId());
        if (detail != null)
            poCourseSupplierDetail.setSupplierPaidAmount(detail.getSupplierPaidAmount());
        if (poCourseSupplierDetail.getEstimatedGenerationCost() != null && poCourseSupplierDetail.getSupplierPaidAmount() != null) {
            Double newDouble = poCourseSupplierDetail.getEstimatedGenerationCost().doubleValue() - poCourseSupplierDetail.getSupplierPaidAmount().doubleValue();
            poCourseSupplierDetail.setSupplierUnpaidAmount(BigDecimal.valueOf(PmpUtil.getScale(newDouble, 2)));
        }
    }


}
